package cn.xsly.ymcc.mq.consumer;

import cn.xsly.ymcc.constants.MQConstants;
import cn.xsly.ymcc.domain.PayOrder;
import cn.xsly.ymcc.dto.PayMsgInMQ;
import cn.xsly.ymcc.service.IPayOrderService;
import cn.xsly.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;


@Component
@Slf4j
@RocketMQMessageListener(topic = MQConstants.TOPIC_ORDER,
        selectorExpression = MQConstants.TAGS_ORDER,
        consumerGroup = MQConstants.CONSUMER_GROUP_ORDER,
        messageModel = MessageModel.CLUSTERING)
public class CourseOrderConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IPayOrderService payOrderService;


    @Override
    public void onMessage(MessageExt message) {
        AssertUtil.isNotNull(message,"消息为空");
        byte[] body = message.getBody();
        String s = new String(body, StandardCharsets.UTF_8);
        PayMsgInMQ payMsgInMQ = JSON.parseObject(s, PayMsgInMQ.class);
        PayOrder pay = payOrderService.selectById(payMsgInMQ.getOrderNo());
        AssertUtil.isNull(pay, "支付单已创建");
        //保存支付单
        pay = new PayOrder();
        BeanUtils.copyProperties(payMsgInMQ, pay);
        pay.setCreateTime(new Date());
        pay.setPayStatus(0);
        payOrderService.insert(pay);
    }
}

